<template>
  <!--评论-->
  <div class="comments">
    <div class="direct-top" v-if="isDirectMessages">
      <div class="cancel" @click="cancel"><i class="el-icon-arrow-left"></i></div>
      <div class="nickname">{{directNickname}}</div>
    </div>
    <!--聊天区域-->
    <div id="chat-box">
<!--      <el-button type="text" @click="loading">加载历史记录</el-button>-->
      <div class="chat-item" v-for="messageItem in messageList">
        <!--聊天时间-->
        <div class="chat-time" v-if="!messageItem.isNow">
          <span>{{ (messageItem.time * 1000)|dateFormat(messageItem.timeType) }}</span>
        </div>
        <div v-else style="height:10px;"></div>
        <div class="chat-content-wrapper" :class="{floatRight: messageItem.flow!=='in'}">
          <!--头像  对方 自己 其他-->
          <img :src="`https://tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/${messageItem.avatar}`" class="chat-avatar" style="margin-left: 10px;"
               v-if="messageItem.flow==='out'">
          <el-dropdown
            placement="bottom-start"
            trigger="click"
            v-if="messageItem.flow==='in' && !isDirectMessages"
            @command="handleCommand">
            <img :src="`https://tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/${messageItem.avatar}`" class="chat-avatar" style="margin-right:10px;cursor:pointer;">
            <el-dropdown-menu slot="dropdown" style="width:130px;">
              <el-dropdown-item :command="{type:'banned',id:messageItem.from}">禁言</el-dropdown-item>
              <el-dropdown-item :command="{type:'toBlacklist',id:messageItem.from}">拉入黑名单</el-dropdown-item>
              <el-dropdown-item :command="{type:'directMessages',id:messageItem.from,nickname:messageItem.nick}">私信</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <img v-if="messageItem.flow==='in' && isDirectMessages" :src="`https://tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/${messageItem.avatar}`" class="chat-avatar" style="margin-right:10px;cursor:pointer;">
          <!--文本信息-->
          <div class="msg-content" v-if="messageItem.type==='TIMTextElem'">
            <!--                  &lt;!&ndash;昵称&ndash;&gt;-->
            <!--                  <div v-if="messageItem.flow==='in'" class="chat-nick-name">-->
            <!--                    <span>{{ messageItem.nick }}</span>-->
            <!--                  </div>-->
            <div class="content-text" :class="{rightContentText: messageItem.flow!=='in'}">
              <span v-for="textItem in decodeText(messageItem.payload.text)">
                <span v-if="textItem.name==='text'">{{ textItem.text }}</span>
                <!--表情包-->
                <img v-if="textItem.name==='emoji'" :src="`${$store.state.emojiPrefix}/emoji/${textItem.src}`"
                     style="width:23px;height:23px;position: relative;top:5px;"/>
              </span>
            </div>
          </div>
          <!--图片消息-->
          <div class="msg-content" v-if="messageItem.type==='TIMImageElem'">
            <!--昵称-->
            <div v-if="messageItem.flow==='in'" class="chat-nick-name">
              <span>{{ messageItem.nick }}</span>
            </div>
            <el-image src="@/project/assets/images/logo.jpg" class="msg-image"
                      :preview-src-list="['@/project/assets/images/logo.jpg']">
            </el-image>
          </div>
        </div>
      </div>
    </div>
    <!--底部输入框和功能区域-->
    <div class="input-module">
      <div class="input-module-top">
        <div class="other-features">
          <!-- 表情框 -->
          <div class="emoji" @click="showEmoji">
            <!--表情包按钮-->
            <img src="./biaoqing.jpg" style="width:30px;height:30px;"/>
            <!--                  <span class="iconfont icon-biaoqing" @click="showEmoji">表情包</span>-->
            <div class="emoji-wrapper" v-if="isShowEmoji">
              <img
                v-for="(val, key, index) in emojiMap"
                :key="index"
                class="emoji-item"
                width="20px"
                :src="`${$store.state.emojiPrefix}/emoji/${emojiMap[key]}`"
                @click="handleSelectEmoji(key,index)"
              />
            </div>
          </div>
          <!--图片上传-->
          <div class="upload-img" @click="handleClickSendImage">
            <img src="./picture.jpg" style="width:30px;height:30px;">
            <!-- 图片上传（隐藏按钮）-->
            <input type="file" id="imagePicker" ref="imagePicker" accept=".jpg, .jpeg, .png" @change="sendImage" style="display:none"/>
          </div>
          <!--机器人-->
          <div
            class="robot"
            @click="openRobot"
            v-if="!isDirectMessages">
            <img src="./robot.jpg" style="width:30px;height:30px;"/>
          </div>
        </div>
        <!--发送按钮-->
        <el-button @click="sendMsg" type="primary">发送</el-button>
      </div>
      <div class="input-module-bottom">
         <textarea
           ref="txtDom"
           placeholder="聊天吧..."
           v-model="content"
           @keyup.enter.exact="sendMsg"
           v-if="isDirectMessages"
         ></textarea>
        <textarea
          ref="txtDom"
          placeholder="跟大家聊天吧..."
          v-model="content"
          @keyup.enter.exact="sendMsg"
          v-else
        ></textarea>
      </div>
    </div>
    <robot @close="closeRobot" :is-robot="isRobot"></robot>
  </div>
</template>

<script>
import {emojiMap} from '../../utils/emojiMap'
import Robot from "../dialog/live/list/robot";
import genTestUserSig from '@/framework/utils/GenerateTestUserSig.js'
import {decodeText} from '@/framework/utils/decodeText'
import {mapActions} from "vuex"
import {save as saveBarrage,findByLive as findBarrageByLive} from '@/project/service/barrage'
import {save as banned} from '@/project/service/mute'
import {saveByUser} from "@/project/service/black"
import {save as saveDirectMsg,} from '@/project/service/privateChatRecord'
import COS from "cos-js-sdk-v5";
import tim from '@/framework/utils/tim.js';
import TIM from 'tim-js-sdk';


export default {
  name: "comments",
  props:{
    //直播间id
    liveId:{
      type: String,
      default: ''
    },
    //私聊对象id
    userId:{
      type: String,
      default: ''
    },
    isDirectMessages:{
      type: Boolean,
      default: false
    },
    directNickname:{
      type: String,
      default: ''
    },
  },
  data(){
    return{
      content:'',//用户输入内容
      isShowEmoji:false,//是否显示表情包框
      //聊天消息列表
      messageList: [
        {
          payload:{
            text:''
          }
        }
      ],
        // [
        // {flow:'out',nick:'小明',type:'TIMTextElem',text:'是否包邮？',time:1657655566},
        // {flow:'out',nick:'小红',type:'TIMTextElem',text:'是否包邮？',time:1657855682},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'顺丰包邮',time:1657859995},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'质量可靠吗？',time:1657855765},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'支持转转验机，这样你我都放心。',time:1657855766},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'好',time:1657855775},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'支持转转验机，这样你我都放心。',time:1657855776},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'好',time:1657855885},
        // {flow:'in',nick:'小刚',type:'TIMTextElem',text:'是否包邮？',time:1657859995},
        // ],
      decodeText: decodeText,//处理消息中的表情包
      isNow: false,//消息的时间是否接近
      isRobot:false,//是否打开机器人对话框
      emojiMap:emojiMap,//表情包转换
      currentChatId: '',//当前聊天的客户id 相当于群聊id 当前聊天的id
      currentUserId: '',//当前聊天的用户id（查聊天记录、保存聊天记录使用）
    }
  },
  components:{ Robot },
  watch:{
    '$store.state.messageList':{
      handler(val){
        this.messageList = val.slice()
        //处理消息时间
        this.handleTime(this.messageList)
      },
      deep: true, //true 深度监听
    }
  },
  filters: {
    // 时间处理过滤器
    dateFormat(dateStr, time) {
      if (dateStr) {
        var date = new Date(dateStr)
        var year = date.getFullYear()
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        var hh = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        if (time && time.toLowerCase() === 'hh:mm') {
          return `${hh}:${mm}`
        } else {
          return `${year}-${month}-${day} ${hh}:${mm}`
        }
      } else {
        return ''
      }
    },
  },
  created(){
    console.log('直播间Id：'+this.liveId)
    console.log('私聊对象Id：'+this.userId)

    //腾讯云im登录
    this.onLogin({
      userID: this.$store.state.user.id + "",
      userSig: genTestUserSig(this.$store.state.user.id + "").userSig
    })

    this.currentChatId = this.isDirectMessages ? this.userId : this.liveId //聊天对象id
    this.currentUserId = this.$store.state.user.id //自己的id
    console.log('自己的id',this.$store.state.user.id)

    console.log('当前聊天对象id：',this.currentChatId)

    //存储当前聊天对象的id
    this.$store.commit('SAVE_CURRENT_CHAT_ID', this.currentChatId)
    localStorage.currentChatId = this.currentChatId

    if(this.isDirectMessages){ //私聊
      this.$store.dispatch('getMessageList', 'C2C' + this.currentChatId + '')//获取私聊聊天内容列表
    }

    //获取store中的消息列表
    this.messageList = this.$store.state.messageList.slice()

    //处理消息时间
    this.handleTime(this.messageList)
  },
  mounted(){
    //设置聊天消息框滚动条在底部
    this.scrollToBottom('#chat-box')
  },
  updated(){
    //设置聊天消息框滚动条在底部
    this.scrollToBottom('#chat-box')
  },
  methods:{
    ...mapActions(['onLogin']),
    //加入群聊
    joinGroup(){

    },
    //处理时间
    handleTime(list){
      if(list.length>0){
        //判断消息之间的时间间隔是否大于60秒大于则下一条显示发送时间
        for(let i=0;i<list.length-1;i++) {
          if (i == 0) {
            list[i].isNow = false
          }
          let gap = list[i + 1].time - list[i].time
          if (gap > 60) {
            list[i + 1].isNow = false
          } else {
            list[i + 1].isNow = true
          }
        }
        //判断消息是否是当天发送的，是的话将时间格式改为'hh:mm'
        list.forEach(item => {
          //获取当天日期
          let date = new Date()
          let year = date.getFullYear()
          let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
          let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
          //获取消息发送的日期
          let messageDate = new Date(item.time*1000)
          let messageYear = messageDate.getFullYear()
          let messageMonth = messageDate.getMonth() + 1 < 10 ? '0' + (messageDate.getMonth() + 1) : messageDate.getMonth() + 1
          let messageDay = messageDate.getDate() < 10 ? '0' + messageDate.getDate() : messageDate.getDate()
          //判断两个日期是否相同，相同则设置时间格式
          if(`${year}${month}${day}`==`${messageYear}${messageMonth}${messageDay}`){
            item.timeType = 'hh:mm'
          }
        })
      }
    },
    //使聊天框的滚动条保持在最底部
    scrollToBottom(id){
      this.$nextTick(()=>{
        let box = this.$el.querySelector(id)
        box.scrollTop = box.scrollHeight
      })
    },
    // 展开表情框
    showEmoji() {
      // if (!this.currentChatId) {
      //   this.$message.error('请选择聊天对象')
      //   this.isShowEmoji = false
      // } else {
      //   this.isShowEmoji = true
      // }
      this.isShowEmoji = !this.isShowEmoji
    },
    // 选择表情执行的操作
    handleSelectEmoji(key, index) {
      // console.log(key,2222)
      this.content = (this.content || '') + key
      this.$refs.txtDom.focus()
    },
    // 发送图片消息
    handleClickSendImage() {
      // if (!this.currentChatId) {
      //   this.$message.error('请选择聊天对象')
      //   return
      // }
      this.$refs.imagePicker.click()
    },
    //发送图片消息
    sendImage(file) {
      let files = file.target.files[0]
      console.log(files)

      // // 初始化实例
      // var cos = new COS({
      //   SecretId: 'AKID3vXu0pNedMnysVsymJZYYHjvpSothDSQ',
      //   SecretKey: 'i9JDwOaU8UdW9VZMs75lAJAl59wSgeMm',
      // })
      // //上传图片
      // cos.uploadFile({
      //   Bucket: 'tencentyun-ms-1312352800', /* 必须 */
      //   Region: 'ap-guangzhou',             /* 存储桶所在地域，必须字段 */
      //   Key: `/image/${files.name}`,        /* 必须 */
      //   Body: files,                        /* 必须 */
      //   SliceSize: 1024 * 1024 * 5,         /* 触发分块上传的阈值，超过5MB使用分块上传，非必须 */
      //   onFileFinish: function (err, data, options) {   /* 非必须 */
      //     console.log(options.Key + '上传' + (err ? '失败' : '完成'));
      //   },
      // }, function(err, data) {
      //   console.log(err || data);
      //   let reg = new RegExp("tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/","g");
      //   data.Location = data.Location.replace(reg,"");
      // })

      tim.createImageMessage(options);
    },
    // 发送文本消息
    sendMsg(){
      if (!this.currentChatId) {
        this.$message.error('请选择聊天对象')
        return
      }
      if (this.content === '' || this.content.trim().length === 0) {
        this.content = ''
        this.$message.error('不能发送空消息')
        return
      }

      console.log(this.currentChatId)

      const message = tim.createTextMessage({
        to: this.currentChatId + '',
        conversationType: this.isDirectMessages ? TIM.TYPES.CONV_C2C : TIM.TYPES.CONV_GROUP,
        payload: {text: this.content}
      })
      tim.sendMessage(message).then(() => {
        this.$store.commit('updateMsgList', message)
        console.log('发送文本消息成功', this.currentChatId + '')
        this.isShowEmoji = false

        if(!this.isDirectMessages){ //群聊
          //上传消息内容到服务器
          let param = {
            barrage:{
              content:this.content,
              live:{id:this.currentChatId}
            }
          }
          this.content = ''
          console.log(param)
          saveBarrage(param,data => {
            console.log(data)
          })
        }else{ //私信
          // console.log('私信')
          let param = {
            privateChatRecord:{
              live:{id:'402703536720445440'},
              user:{id:this.currentChatId}
            }
          }
          console.log(param)
          this.content = ''
          saveDirectMsg(param, data => {
            console.log(data)
          })
        }
      })

      console.log('新的消息列表数据',this.messageList)
    },
    //打开机器人对话框
    openRobot(){
      this.isRobot = true
    },
    //关闭机器人对话框
    closeRobot(isRobot){
      this.isRobot = isRobot
    },
    //加载历史记录
    loading(){
      if(this.isDirectMessages){ //私聊

      }else{ //群聊

      }
    },
    //用户操作
    handleCommand(info){
      switch (info.type){
        case 'banned':
          this.banned(info.id)
          break
        case 'toBlacklist':
          this.toBlacklist(info.id)
          break
        case 'directMessages':
          this.directMessages(info)
          break
      }
    },
    //禁言
    banned(id){
      let param = {
        mute:{
          // live:{id: this.liveId}
          live:{id: this.currentChatId},
          user:{id: id}
        },
      }
      console.log(param)
      banned(param, data => {
        console.log(data)
        this.$message.success('禁言成功')
      })
    },
    //拉入黑名单
    toBlacklist(id){
      let param = {userId:id}
      console.log(param)
      // saveByUser(param,data => {
      //   console.log(data)
      //   if(data == '204'){
      //     this.$message.success('用户已被加入黑名单')
      //   }
      // })
    },
    //私信
    directMessages(info){
      this.$emit('toDirect',info)
    },
    //私信页返回
    cancel(){
      this.$emit('close')
    },
  }
}
</script>

<style lang="less" scoped>
//评论
.comments{
  background-color: rgb(251, 251, 251);

  .direct-top{
    border: 1px solid rgb(220, 223, 230);
    height: 38px;
    padding-left: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .cancel{
      font-size: 25px;
      position: absolute;
      left:10px;
      cursor:pointer;
    }

    .nickname{
      width: 200px;
      text-align: center;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
    }
  }

  #chat-box{
    height: 500px;
    width: 99.5%;
    border-left: 1px solid rgb(220, 223, 230);
    border-right: 1px solid rgb(220, 223, 230);
    border-bottom: 1px solid rgb(220, 223, 230);
    background-color: rgb(255, 255, 255);
    overflow-y: auto;
    padding-bottom:20px;

    .chat-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .chat-time {
        text-align: center;
        width: 200px;
        color: rgb(169, 155, 165);
        font-size: 14px;
        margin-bottom: 10px;
        padding: 2px 10px;
        border-radius: 5px;
        margin: 20px 0;
      }
      .chat-nick-name{
        width: 120px;
        font-size: 12px;
        padding: 2px 10px;
      }

      .chat-content-wrapper {
        display: flex;
        width: 100%;
        box-sizing: border-box;
        padding: 0 10px;

        &.floatRight {
          flex-direction: row-reverse;
        }

        .el-dropdown{
          height:35px;
        }

        .chat-avatar {
          width: 35px;
          height: 35px;
          border-radius: 50%;
        }

        .msg-content{
          display: flex;
          align-items: center;

          .content-text {
            background-color: rgb(240, 242, 245);
            padding: 8px 10px;
            border-radius: 5px;
            font-size: 14px;
            max-width: 250px;
            word-break: break-all;
            min-width: 10px;

            &.rightContentText{
              background-color: rgb(109, 156, 248);
              color: white;
              padding: 8px 10px;
              border-radius: 5px;
              font-size: 14px;
              max-width: 250px;
              word-break: break-all;
              min-width: 10px;
            }
          }
        }
      }
    }
  }

  .input-module-top{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-left: 1px solid rgb(220, 223, 230);
    border-right: 1px solid rgb(220, 223, 230);
    padding:0 10px;
    background-color: rgb();

    .el-button{
      height:30px;
    }

    .other-features{
      height:100%;
      position: relative;
      display: flex;
      align-items: center;

      .emoji{
        margin-right: 10px;
        width:30px;
        height:30px;
        cursor: pointer;

        .emoji-wrapper {
          background-color: #fff;
          width: 250px;
          height: 170px;
          padding: 20px 0 20px 10px;
          position: absolute;
          top: -200px;
          left: 10px;
          box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
          border-radius: 10px;
          user-select: none;
          overflow-y: scroll;

          .emoji-item {
            margin-right: 3px;
            cursor: pointer;
          }
        }
      }

      .upload-img{
        width:30px;
        height:30px;
        margin-right: 10px;
        cursor: pointer;
      }

      .robot{
        width:30px;
        height:30px;
        cursor: pointer;
      }
    }
  }

  .input-module-bottom{
    height: 150px;

    textarea {
      outline: none;
      height: 100%;
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      font-size: 16px;
      font-weight: bold;
      line-height: 20px;
      border: 1px solid rgb(220, 223, 230);
      resize: none;

      &.disabled {
        cursor: not-allowed;
      }
    }
  }
}
</style>
